<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 注意 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择 -->
      <el-row>
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            v-model="paraValue"
            :options="dataList"
            :props="paraProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isclick"
            @click="addEdit"
          >添加参数</el-button>
        </el-tab-pane>
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isclick"
            @click="addEdit"
          >添加属性</el-button>
        </el-tab-pane>

        <!-- 表格部分 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          stripe
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag
                closable
                class="tag"
                v-for="(item,index) in scope.row.attr_vals"
                :key="index"
                @close="valsClick(index,scope.row)"
              >
                {{item}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="tagInputRef"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
              >+ New Tag</el-button>
            </template>
          </el-table-column>

          <el-table-column type="index"></el-table-column>
          <el-table-column
            prop="attr_name"
            :label="label"
          >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="bjDataClick(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteDataClick(scope.row)"
              >删除</el-button>
            </template>

          </el-table-column>
        </el-table>
      </el-tabs>
    </el-card>

    <!-- 添加属性（参数）对话框 -->
    <el-dialog
      :title="titleDialog"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClosed"
      :lock-scroll="false"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editRef"
        label-width="100px"
      >
        <el-form-item
          :label="formLabel"
          prop="attr_name"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addEditData"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="bjDialogVisible"
      width="50%"
      :lock-scroll="false"
    >
      <el-form
        :model="bjDataList"
        :rules="bjRules"
        ref="bjRef"
        label-width="100px"
      >
        <el-form-item
          label="静态属性"
          prop="attr_name"
        >
          <el-input v-model="bjDataList.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="bjDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="bjData"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getData, setData, putData, deleteData } from "network/goodsPara";
export default {
  data() {
    return {
      dataList: [],

      paraValue: [],

      paraProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      activeName: "many",
      manyList: [],
      onlyList: [],

      editDialogVisible: false,
      bjDialogVisible: false,

      editForm: {
        attr_name: ""
      },
      editRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      bjDataList: {},
      bjRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      attr_id: null
    };
  },
  methods: {
    getData() {
      getData("categories").then(res => {
        if (res.data.meta.status === 200) {
          // console.log(res);
          this.dataList = res.data.data;
        }
      });
    },

    handleChange() {
      this.getparaData();
    },
    handleClick() {
      this.getparaData();
    },
    getparaData() {
      if (this.paraValue.length !== 3) {
        this.paraValue = [];
        this.manyList = [];
        this.onlyList = [];
        return;
      }
      getData(`categories/${this.cartId}/attributes`, {
        sel: this.activeName
      }).then(res => {
        if (res.data.meta.status === 200) {
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
            item.inputVisible = false;
            item.inputValue = "";
          });
          if (this.activeName === "many") {
            this.manyList = res.data.data;
            console.log(this.manyList);
          } else {
            this.onlyList = res.data.data;
            // console.log(this.onlyList);
          }
        } else {
          this.$Message.error(res.data.meta.msg);
        }
      });
    },
    addEdit() {
      this.editDialogVisible = true;
    },
    editClosed() {
      this.$refs.editRef.resetFields();
    },
    addEditData() {
      this.$refs.editRef.validate(valid => {
        if (!valid) return;
        setData(`categories/${this.cartId}/attributes`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }).then(res => {
          if (res.data.meta.status === 201) {
            this.getparaData();
            this.editDialogVisible = false;
            this.$Message.success(res.data.meta.msg);
          } else {
            this.$Message.error(res.data.meta.msg);
          }
        });
      });
    },
    bjDataClick(data) {
      this.attr_id = data.attr_id;
      getData(`categories/${this.cartId}/attributes/${data.attr_id}`, {
        attr_sel: this.activeName
      }).then(res => {
        if (res.data.meta.status === 200) {
          this.bjDataList = res.data.data;
        } else {
          this.$Message.error(res.data.meta.msg);
        }
      });
      this.bjDialogVisible = true;
    },
    bjData() {
      putData(`categories/${this.cartId}/attributes/${this.attr_id}`, {
        attr_name: this.bjDataList.attr_name,
        attr_sel: this.activeName
      }).then(res => {
        if (res.data.meta.status === 200) {
          this.getparaData();
          this.$Message.success("修改成功！");
          this.bjDialogVisible = false;
        } else {
          this.$Message.error("修改失败！");
        }
      });
    },
    async deleteDataClick(data) {
      const isTrue = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(isTrue)
      if (isTrue === "cancel") {
        this.$Message.info("取消删除！");
      } else {
        deleteData(`categories/${this.cartId}/attributes/${data.attr_id}`).then(
          res => {
            if (res.data.meta.status === 200) {
              this.$Message.success(res.data.meta.msg);
              this.getparaData();
            } else {
              this.$Message.error(res.data.meta.msg);
            }
          }
        );
      }
    },
    handleInputConfirm(row) {
			if(row.inputValue.trim().length === 0){
				row.inputValue = ''
				row.inputVisible = false
				return
			}
			row.attr_vals.push(row.inputValue.trim())
			row.inputValue = ''
			row.inputVisible = false
			this.putValsData(row)
    },
    putValsData(row){
      putData(`categories/${this.cartId}/attributes/${row.attr_id}`,{attr_name : row.attr_name,attr_sel : row.attr_sel,attr_vals : row.attr_vals.join(' ') }).then(res => {
				// console.log(res)
				if(res.data.meta.status === 200){
					// this.getparaData()
					this.$Message.success(res.data.meta.msg)
				}else{
					this.$Message.error(res.data.meta.msg)
				}
			})
    },
    showInput(row) {
			row.inputVisible = true;
			// $nextTick等页面加载完执行
      this.$nextTick(_ => {
        this.$refs.tagInputRef.$refs.input.focus();
      });
    },
    valsClick(index,row){
      row.attr_vals.splice(index,1)
      this.putValsData(row)
    }
  },
  computed: {
    isclick() {
      if (this.paraValue.length !== 3) {
        return true;
      }
      return false;
    },
    cartId() {
      if (this.paraValue.length === 3) {
        return this.paraValue[2];
      }
      return null;
    },
    tableData() {
      return this.activeName === "many" ? this.manyList : this.onlyList;
    },
    label() {
      return this.activeName === "many" ? "参数名称" : "属性名称";
    },
    titleDialog() {
      return this.activeName === "many" ? "添加动态参数" : "添加静态属性";
    },
    formLabel() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    }
  },
  created() {
    this.getData();
  }
};
</script>
<style scoped>
.el-card {
  margin: 20px 0;
}
.el-row {
  margin-top: 15px;
}
.tag {
  margin: 0 5px;
}
.input-new-tag {
  width: 120px;
}
</style>